<!--
  * 线路
  *
-->
<template>
  <!---------- 查询表单form begin ----------->
  <a-card size="small" :bordered="false" :hoverable="false" class="query-form-wrapper smart-margin-bottom10 smart-radius-2">
    <a-form>
      <a-row :gutter="[8, 10]">
        <a-col :span="5">
          <a-form-item label="门店名称" class="smart-margin-bottom0">
            <a-input v-model:value.trim="queryForm.store_name" placeholder="门店名称" allow-clear />
          </a-form-item>
        </a-col>
        <a-col :span="4">
          <a-form-item label="门店类型" class="smart-margin-bottom0">
            <Select name="Level" v-model:value="queryForm.store_level_id" placeholder="门店类型" @input-enter="onSearch" />
          </a-form-item>
        </a-col>
        <a-col :span="4">
          <a-form-item label="片区" class="smart-margin-bottom0">
            <Select name="Region" v-model:value="queryForm.store_region_id" placeholder="片区" @input-enter="onSearch" />
          </a-form-item>
        </a-col>
        <a-col :span="5">
          <a-button-group>
            <a-button type="primary" html-type="submit" @click="onSearch" v-privilege="'goods:query'">
              <template #icon>
                <SearchOutlined />
              </template>
              查询
            </a-button>
            <a-button @click="resetQuery" v-privilege="'goods:query'">
              <template #icon>
                <ReloadOutlined />
              </template>
              重置
            </a-button>
          </a-button-group>
        </a-col>
      </a-row>
    </a-form>
  </a-card>
  <!---------- 查询表单form end ----------->

  <a-card size="small" :bordered="false" :hoverable="true" class="query-table-wrapper">
    <!---------- 表格操作行 begin ----------->
    <a-row class="smart-table-btn-block">
      <div class="smart-table-operate-block">
        <a-button @click="add()" type="primary" v-privilege="'goods:add'" v-if="lineId">
          <!-- <template #icon>
            <PlusOutlined />
          </template> -->
          绑定门店
        </a-button>

        <a-button @click="confirmBatchDelete" danger :disabled="selectedRowKeyList.length === 0" v-privilege="'goods:batchDelete'" v-if="lineId">
          <template #icon>
            <DeleteOutlined />
          </template>
          批量移除
        </a-button>
      </div>
      <div class="smart-table-setting-block">
        <TableOperator v-model="columns" :tableId="TABLE_ID_CONST.BUSINESS.ERP.GOODS" :refresh="queryData" />
      </div>
    </a-row>
    <!---------- 表格操作行 end ----------->
    <div class="table-wrapper">
      <a-table size="small" :dataSource="tableData" :columns="columns" rowKey="id" bordered :scroll="{ x: 'max-content', y: tableScrollY }" :pagination="false" :showSorterTooltip="false" :loading="tableLoading" :row-selection="{ selectedRowKeys: selectedRowKeyList, onChange: onSelectChange }">
        <template #bodyCell="{ text, record, column }">
          <template v-if="column.dataIndex === 'action'">
            <div class="smart-table-operate">
              <a-button @click="onDelete(record)" danger type="link" v-privilege="'goods:delete'" v-if="lineId">移除</a-button>
            </div>
          </template>
        </template>
      </a-table>
    </div>

    <div class="smart-query-table-page query-table-page">
      <a-pagination showSizeChanger showQuickJumper show-less-items :pageSizeOptions="PAGE_SIZE_OPTIONS" :defaultPageSize="queryForm.limit" v-model:current="queryForm.page" v-model:pageSize="queryForm.limit" :total="total" @change="queryData" @showSizeChange="queryData" :show-total="(total) => `共${total}条`" />
    </div>
    <!-- 绑定门店 -->
    <StoreFormModal ref="formModal" @reloadList="queryData" />
  </a-card>
</template>
<script setup lang="ts">
import _ from 'lodash'
import StoreFormModal from './components/store-form-modal.vue'
import { message, Modal } from 'ant-design-vue'
import { errorSentry } from '@/lib/error-sentry'
import { lineApi } from '@/api/business/data/line-api'
import Select from '@/components/business/select/index.vue'
import { PAGE_SIZE_OPTIONS } from '@/constants/system/common-const'
import TableOperator from '@/components/support/table-operator/index.vue'
import { TABLE_ID_CONST } from '@/constants/support/table-id-const'
import { useQuery } from '@/hooks/web/use-query-hook'
import { useAppConfigStore } from '@/store/modules/app-store'
import { useResize } from '@/hooks/web/use-resize-hook'
import eventEmitter from '@/lib/event-emitter'
import { useLoadingStore } from '@/store/modules/loading-store'
const appConfigStore = useAppConfigStore()
const loadingStore = useLoadingStore()
// ----------------------------- 计算表格高度 -----------------------------
const { tableScrollY } = useResize()

// ---------------------------- 表格列 ----------------------------

const columns = computed(() => [
  {
    title: '门店名称',
    dataIndex: 'store_name'
  },
  {
    title: '负责人',
    dataIndex: 'contacts'
  },
  {
    title: '联系电话',
    dataIndex: 'phone'
  },
  {
    title: '门店类型',
    dataIndex: ['level', 'level_name']
  },
  {
    title: '所属片区',
    dataIndex: ['region', 'name']
  },
  {
    title: '地址',
    dataIndex: 'address'
  },
  {
    title: '操作',
    dataIndex: 'action',
    fixed: 'right',
    width: appConfigStore.$state.compactFlag ? 80 : 100
  }
])
// const refreshTable = () => {
//   lineId.value = ''
//   resetQuery()
//   eventEmitter.emit('Custom:refreshData')
// }
// ---------------------------- 查询数据表单和方法 ----------------------------
const { queryForm, tableData, tableLoading, total, resetQuery, onSearch, queryData, deleteData, setQuery } = useQuery({
  fetchDataApi: async (params) => {
    const data = {
      ...params,
      id: lineId.value,
      store_name: queryForm.value.store_name,
      store_level_id: queryForm.value.store_level_id,
      store_region_id: queryForm.value.store_region_id
    }
    const res = await lineApi.lineStoreList(data)
    return {
      list: res.data.data,
      total: res.data.total
    }
  },
  queryFormFilter: {},
  queryFormOp: {}
})

// ---------------------------- 线路ID ----------------------------
const lineId = ref('')
function dataLine(record) {
  lineId.value = record.id
}

// ---------------------------- 添加/修改 ----------------------------
const formModal = ref()

function add() {
  formModal.value.showDrawer(tableData.value, lineId.value)
}

// ---------------------------- 单个移除 ----------------------------
//确认移除
function onDelete(data) {
  Modal.confirm({
    title: '提示',
    content: `确定要移除${data.store_name}吗?`,
    okText: '移除',
    okType: 'danger',
    onOk() {
      requestDelete(data)
    },
    cancelText: '取消',
    onCancel() {}
  })
}

//请求移除
async function requestDelete(data) {
  loadingStore.show()
  try {
    const params = {
      id: lineId.value,
      store_ids: data.id
    }
    await lineApi.lineDelStore(params)
    message.success('移除成功')
    queryData()
  } catch (e) {
    errorSentry.captureError(e)
  } finally {
    loadingStore.hide()
  }
}

// ---------------------------- 批量移除 ----------------------------

// 选择表格行
const selectedRowKeyList = ref([])

function onSelectChange(selectedRowKeys) {
  selectedRowKeyList.value = selectedRowKeys
}

// 批量移除
function confirmBatchDelete() {
  Modal.confirm({
    title: '提示',
    content: '确定要批量移除这些数据吗?',
    okText: '移除',
    okType: 'danger',
    onOk() {
      requestBatchDelete()
    },
    cancelText: '取消',
    onCancel() {}
  })
}

//请求批量移除
async function requestBatchDelete() {
  try {
    loadingStore.show()
    const params = {
      id: lineId.value,
      store_ids: selectedRowKeyList.value.join(',')
    }
    await lineApi.lineDelStore(params)
    message.success('移除成功')
    selectedRowKeyList.value = []
    queryData()
  } catch (e) {
    errorSentry.captureError(e)
  } finally {
    loadingStore.hide()
  }
}

defineExpose({
  queryData,
  dataLine
})
</script>
